import React, { FC, useEffect, useState } from 'react'
import { Pagination } from 'antd'
import { useSearchParams, useNavigate, useLocation } from 'react-router-dom'
import { LIST_PAGE_SIZE_PARAM_KEY, LIST_PAGE_PARAM_KEY } from '../constant'

type IPage = {
  total: number
}
const ListPage: FC<IPage> = (props: IPage) => {
  const nav = useNavigate()
  const { pathname } = useLocation()
  const [searchParams] = useSearchParams()
  const [pageSize, setPageSize] = useState(1)
  const [page, setPage] = useState(15)

  useEffect(() => {
    const curPage = Number(searchParams.get(LIST_PAGE_PARAM_KEY)) || 1
    const curPageSize = Number(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY)) || 15
    setPageSize(curPageSize)
    setPage(curPage)
  }, [searchParams])
  const handlePageChange = (page: number, pageSize: number) => {
    searchParams.set(LIST_PAGE_PARAM_KEY, page.toString())
    searchParams.set(LIST_PAGE_SIZE_PARAM_KEY, pageSize.toString())
    nav({
      pathname,
      search: searchParams.toString(), // 除了改变 page pageSize 之外，其他的 url 参数要带着
    })
  }
  return (
    <Pagination
      onChange={handlePageChange}
      current={page}
      pageSize={pageSize}
      defaultCurrent={page}
      total={props.total}
    />
  )
}
export default ListPage
